<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
	<view class="home-item-container">
		<!-- 这里设置了z-paging加载时禁止自动调用reload方法，自行控制何时reload（懒加载）-->
		<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
		<z-paging ref="paging" v-model="dataList" 
		:loading-more-enabled="activeItem == 0"	
		:default-page-size="activeItem == 0?6:5"
		@query="queryList" @scroll="pageScrollFn" :refresher-background="'#FAE7B9'" :hide-no-more-inside="true" :fixed="false" :auto="true">
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
			<template #refresher="{refresherStatus}" style="height: 200rpx;">
						<!-- 此处的custom-refresh为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，下拉刷新就显示什么view -->
				<image src="/static/home/refreshLoading.gif" mode="heightFix" style="height: 100rpx;margin: 0 auto;display: block;"></image>
				<view class="u-text-center">{{statusTextArr[refresherStatus]}}</view>
			</template>
			<!-- 自定义没有更多数据view -->
			<template #loadingMoreNoMore>
				<view class="u-flex u-col-center u-row-center">
					<u-line color="#DFDFDF" length="110rpx"/>
					<view class="u-flex u-m-l-30 u-m-r-30" style="flex-direction: column;align-items: center;">
						<image src="/static/home/noMore.png" mode="heightFix" style="height:50rpx;margin: 0 auto;display: block;"></image>
						<text class="u-font-10 u-m-t-6" style="color:#999">没有更多了</text>
					</view>
					<u-line color="#DFDFDF" length="110rpx"/>
				</view>
			</template>
			<view>
				<view  class="seller-home-top u-p-l-35 u-p-r-35">
					<u-swiper class="u-skeleton-fillet u-m-b-20"  v-if="bannerList.length !==0" :list="bannerList" @click="bannerClick" name="url" :height="304" :border-radius="10"></u-swiper>
					<view class="tab-top-list  u-flex u-row-between">
						<view :class="['tab-item','u-flex','u-row-center',{'tab-item-active':activeItem == 0}]" @tap="activeChange(0)">
							<view class="iconfont icon-tuijian"></view>
							<view class="u-font-30 u-m-l-10">推荐榜</view>
						</view>
						<view :class="['tab-item','u-flex','u-row-center','u-m-l-20','u-m-r-20',{'tab-item-active':activeItem == 1}]" @tap="activeChange(1)">
							<view class="iconfont icon-rexiao"></view>
							<view class="u-font-30 u-m-l-10">热销榜</view>
						</view>
						<view :class="['tab-item','u-flex','u-row-center',{'tab-item-active':activeItem == 2}]" @tap="activeChange(2)">
							<view class="iconfont icon-shoucang"></view>
							<view class="u-font-30 u-m-l-10">收藏榜</view>
						</view>
					</view>
				</view>
				<view class="item-content">
					<!-- <view class="u-flex u-row-between u-m-t-20 u-m-b-30">
						<text>只显示可购买</text>
						<u-switch v-model="isShowBuy" size="40" active-color="#ffbb1a" inactive-color="#ccc" @change="loadAgainFn"></u-switch>
					</view> -->
					<view class="item-list u-m-t-20  u-flex" v-for="(item,index) in dataList" :key="index" @click="itemClick(item)">
						<view class="item-image-container u-m-r-24">
							<image :src="item.url" mode="" class="item-image "></image>
							<image src="/static/xiaoshou/jin.png" v-if="index === 0" mode="" class="item-image-mark"></image>
							<image src="/static/xiaoshou/yin.png" v-if="index ===1" mode="" class="item-image-mark"></image>
							<image src="/static/xiaoshou/tong.png" v-if="index === 2" mode="" class="item-image-mark"></image>
							<view class="item-image-num_mark u-flex u-row-center" v-if="index>2&&index<10">
								{{index+1}}
							</view>
							<view class="item-image-bot u-text-center u-line-1 u-font-24" v-if="activeItem!=0">
								{{activeItem==1?'销售'+item.monthlySalesVolume:'收藏'+item.collectionVolume}}
							</view>
						</view>
						<view class="item-info">
							<view class="u-flex u-row-between" style="flex-direction: column;" >
								<view style="width: 100%;">
									<view class="u-flex u-col-top" @click.stop>
										<view class="item-name u-line-2"  @click="itemClick(item)" style="flex:1;">{{item.itemName}}</view>
											<u-icon name="star" v-if="!item.isCollect" @click="addCollectFn(item.id)" color="#999" size="50" class="u-m-l-20"></u-icon>
											<u-icon name="star-fill" v-else color="#FF831A" @click="removeCollectFn(item.id,item.groupId)" size="50" class="u-m-l-20"></u-icon>
									</view>
									<view class="item-val  u-m-t-14 u-m-b-6" style="border: 1px solid #FF551A;">
										<view class="item-val-text item-val-specifica-title">规格</view>
										<view class="item-val-text item-val-specifica-text">{{item.specification}}</view>
									</view>
									<br />
									<view class="item-val" style="border: 1px solid #C09A87;">
										<view class="item-val-text item-val-owner-title">品牌商</view>
										<view class="item-val-text item-val-owner-text">{{item.brandOwnerName}}</view>
									</view>
								</view>
								<view class="u-flex u-row-between u-col-bottom " style="width: 100%;">
									<view class="u-flex u-col-bottom">
										<view class="item-price u-font-32 u-m-r-20">￥{{item.price}}</view>
										<view class="item-stock u-font-24">{{item.inventoryStatus}}</view>
									</view>
									<view :class="['item-add', 'u-flex', 'u-row-center',{'item-no-add':!item.isPurchasable}]" @click.stop="addItemFn(item)" 
									>
										<view class="u-font-22">加购</view>
										<u-icon name="plus" :color="item.isPurchasable?'#C88D00':'#9d9d9d'" size="18"></u-icon>
									</view>
									<!-- item.isPurchasable&&(item.inventoryBalance>=item.sellingUnit) -->
								</view>
							</view>
						</view>
						<!-- <image src="/static/xiaoshou/noSign.png" mode="" class="no-sign" v-if="!item.isPurchasable"></image> -->
					</view>
				</view>
			</view>
		</z-paging>
		<u-mask :show="showChoseNum" :z-index="888" :custom-style="{background: 'rgba(0, 0, 0, 0.3)'}" @click="showChoseNum = false"></u-mask>
		<view v-if="showChoseNum" class="chose-num box-padding">
			<view class="u-flex u-row-between" style="height: 111rpx; padding-bottom: 20rpx;">
				<text class="text-bold">下单数量</text>
				<number-box box-width="100rpx" width="200rpx" height="50rpx" fontSize="28rpx"
				 :value="quantity"
				  :step="product.sellingUnit?product.sellingUnit:1" 
				  :min="product.sellingUnit?product.sellingUnit:1" 
				  :max="product.inventoryBalance" 
				  @change="updateQuantity"></number-box>
			</view>
			<view class=" u-m-b-30 sellunit-box">
				最小销售单位 {{product.sellingUnit}}  {{product.unit||'瓶'}}
			</view>
			<u-button shape="circle" hover-class="none" :ripple="true" :hair-line="false" :custom-style="getBtStyle('default')" @click.native="AddCartFn">加入购物车</u-button>
		</view>
		<view :class="['shop-cart-container',transformClass?'shop-cart-active':'']" @click="goShopCartFn">
			<u-icon name="shopping-cart" style="font-size: 60rpx;font-weight: bold;"></u-icon>
		</view>
		<u-action-sheet  v-model="chooseGroupShow" :list="groupShowList" :labelName="'name'" @click="addItemGroupFn" safe-area-inset-bottom	></u-action-sheet>
	</view>
</template>

<script>
	import NumberBox from '@/components/number-box/index.vue';
	import { useUserStore } from '@/store/user.js';
	import { useShopStore } from '@/store/shop.js';
	import { mapState } from 'pinia';
	export default {
		components:{ NumberBox },
		data() {
			return {
				activeItem:0,
				bannerList:[],
				dataList: [],
				isShowBuy:true,
				showChoseNum:false,
				product:{},
				quantity:1,
				timer:null,
				transformClass:true,
				statusTextArr: ['哎呀，用点力继续下拉！', '拉疼我啦，松手刷新~~', '正在努力刷新中...', '刷新成功啦~'],
				groupShowList:[],
				chooseGroupShow:false,
				addGroupItemId:'',
				isEmpty:false,
			}
		},
		props:{
			SellerId:{
				type:String,
				default:""
			},
			keyWords:{
				type:String,
				default:""
			},
			searchBrand: {
				type: Array,
				default () {
					return []
				}
			},
			searchClass: {
				type: Array,
				default () {
					return []
				}
			},
			searchOwner: {
				type: Array,
				default () {
					return []
				}
			},
			startPrice:'',
			endPrice:'',
			SortBy:{
				type:Number,
				default:0
			}
		
		},
		created(){
			this.getBannerList();
		},
		computed:{
			...mapState(useUserStore,['isPurchase']),
			...mapState(useShopStore, {storeShop: 'shop'})
		},
		methods: {
			// 获取banner列表
			async getBannerList(){
				let params = {
					BuyerId: this.storeShop.id,
					ShopId:this.SellerId
				}
				const res = await this.$newHttp.get('api/v1.2/ShanNiang/GetBannerForSeller',{params:params});
				
					this.bannerList = res.data.bannerImages;
			},
			bannerClick(val){
				if(this.bannerList[val].linkObjetId!==0){
					if(this.bannerList[val].linkType ===1){
						this.$mRouter.push({
							route: '/pages/index/xiangqing?id=' + this.bannerList[val].linkObjetId + '&sellerShopId=' + this.SellerId
						})
					}
					if(this.bannerList[val].linkType ===2){
						this.$mRouter.push({
							 route: '/pages/index/huodong?id=' + this.bannerList[val].linkObjetId 
						})
					}
				}
			},
			activeChange(val){
				this.activeItem = val;
				this.$refs.paging.reload();
			},
			// 添加商品收藏 打开下拉菜单
			 addCollectFn(id){
				if(this.groupShowList.length == 0){
					 this.getGroupList()
				};
				this.addGroupItemId = id;
				this.chooseGroupShow = true;
			},
			// 移除收藏
			async removeCollectFn(id,groupId){
				uni.showLoading({
					title:'loading...'
				})
				let params = {
					ItemIds: [id],
					groupId:groupId,
				}
				if (groupId === 'default-group'||!groupId) {
					delete params.groupId
				}
				const res = await this.$newHttp.delete('api/v1.2/Favorite/Remove'+this.$u.queryParams(params, true, 'repeat'));
				uni.hideLoading();
				if(res.code === 200){
					uni.showToast({
						title:'删除成功'
					});
					this.$refs.paging.refresh();
				}else{
					this.$u.toast('删除失败,错误信息：'+res.erroMessage, 2000);
				}
			},
			// 添加默认收藏
			async addItemGroupFn(val){
				uni.showLoading({
					title:'loading...'
				})
				let params = {
					itemId: this.addGroupItemId,
					sellerId: this.SellerId,
					groupId:this.groupShowList[val].id
				}
				if (this.groupShowList[val].id === 'default-group') {
					delete params.groupId
				}
				const res = await this.$newHttp.post('api/v1.2/Favorite/Add', params);
				uni.hideLoading();
				if (res.code === 200) {
					this.$u.toast('添加收藏成功', 1000, 'success');
					this.$refs.paging.refresh()
				}else{
					this.$u.toast('添加收藏失败,错误信息：'+res.erroMessage, 2000);
				}
			},
			async getGroupList(){
				const res = await this.$newHttp.get('api/v1.2/Favorite/GetAllGroups');
				if(res.code === 200){
					let ary = [{
						name:'默认',
						id:"default-group"
					}];
					if(res.data.length!=0){
						ary.push(...res.data);
					}
					this.groupShowList = ary;
				}
			},
			// 滚动隐藏购物车
			pageScrollFn(){
				this.transformClass = true; //要添加的class类名
				clearTimeout(this.timer);//这里必须要每次滚动前 清除一次
				// 如果停留则表示滚动结束  一旦空了1s就判定为滚动结束
				this.timer = setTimeout(() => {
				  this.transformClass = false //滚动结束清除class类名
				}, 1500);
			},
			// 添加到购物车
			async AddCartFn(){
				let params = {
					itemId: this.product.id,
					sellerShopId: this.SellerId,
					quantity: this.quantity,
					buyerShopId: this.storeShop.id,
				}
				uni.showLoading({
					title:'loading...'
				})
				const res = await this.$newHttp.post('api/ShoppingCart/AddShoppingCart', params);
				uni.hideLoading();
				if (res.code === 200) {
					this.$u.toast('添加成功', 1000, 'success');
					this.showChoseNum = false;
				}else{
					this.showChoseNum = false;
					this.$u.toast('添加失败', 1000, 'failed');
				}
			},
			loadAgainFn(){
				this.$refs.paging.reload(); 
			},
			// 查看购物车
			goShopCartFn(){
				if(!this.transformClass){
					if (!this.isPurchase) {
						return this.$u.toast('当前账号没有查看购物车的权限，请联系管理员处理~');
					}else{
						uni.navigateTo({
							url: '/pages/sale/homePage/shopCart',
						});
					};
				};
				this.transformClass = false;
			},
			// 添加到购物车弹窗打开
			addItemFn(item){
				if(!this.isPurchase){
					return this.$u.toast('当前账号没有下单的权限，请联系管理员处理~');
				}
				if(!item.isPurchasable){
					return this.$u.toast('您还没有与销售商签约此产品，请联系销售商签约~');
				}
				if(item.inventoryBalance<item.sellingUnit){
					return this.$u.toast('当前商品库存不足~');
				}
				this.quantity = item.sellingUnit;
				this.product = item;
				this.showChoseNum = true;
			},
			// 修改数量
			updateQuantity(value) {
				this.quantity = value
			},
			// 初始化商品数据
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					BuyerId:this.storeShop.id,
					SellerId:this.SellerId,
					// Purchasable:this.isShowBuy,
				}  
				if (this.activeItem == 0) {
					params.SortBy = 3;
						params.IsRecommend = true;
				}
				if (this.activeItem == 1) {
					params.SortBy = 8;
				}
				if (this.activeItem == 2) {
						params.SortBy = 17;
				}
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				const res = await this.$newHttp.get('api/v1.2/ShanNiang/GetSellerGoodsPage?'+this.$mHelper.stringify(params));
				uni.hideLoading({
					title: 'loading...'
				})
				if(res.code === 200){
					this.$refs.paging.complete(res.data.list);
				}else{
					this.$refs.paging.complete(false);
				}
			},
			// 跳转商品详情
			itemClick(item) {
				let auth = item.isPurchasable?1:0;
				this.$mRouter.push({
					route: '/pages/index/xiangqing?id=' + item.id + '&sellerShopId=' + item.sellerShopId + '&auth=' +auth
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/iconfont/iconfont.css';
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.home-item-container {
		height: 100%;
		.seller-home-top{
			background: linear-gradient(180deg, #FAE7B9, #f8f8f8);
			.tab-top-list{
				
				.tab-item{
					flex:1;
					background-color: #F0F0F0;
					color: #999;
					box-sizing: border-box;
					padding: 30rpx 0;
					border-radius: 30rpx 30rpx 0px 0px;		
					.iconfont{
						font-size: 48rpx;
					}
				}
				.tab-item-active{
					background-color: #fff;
					color: #333;
					font-weight: 500;
					.iconfont{
						color:#ff551a;
					}
				}
			}
		}
		.item-content{
			box-sizing: border-box;
			padding: 0 34rpx;
			.item-list{
				background-color: #fff;
				border-radius: 20rpx;
				position: relative;
				.no-sign{
					width: 130rpx;
					height: 130rpx;
					position: absolute;
					top: 0;
					right: 0;
				}
				.item-image-container{
					position: relative;
					width: 230rpx;
					height: 230rpx;
					.item-image-mark{
						width: 54rpx;
						height: 46rpx;
						position: absolute;
						top: -6rpx;
						left: -10rpx;
					}
					.item-image-bot{
						position: absolute;
						width: 100%;
						background: #FFFFFF;
						opacity: 0.7;
						border-top-left-radius: 10rpx;
						border-top-right-radius: 10rpx;
						bottom: -1rpx;
						left: 0;
					}
					.item-image-num_mark{
						top: -8rpx;
						left: -8rpx;
						width: 41rpx;
						height: 41rpx;
						background: #FFEEC7;
						border: 2px solid #DBB160;
						border-radius: 50%;
						position: absolute;
						font-weight: 500;
						color: #D4A336;
					}
				}
				.item-image{
					width: 230rpx;
					height: 230rpx;
					border: 1px solid #E4E4E4;
					border-radius: 10rpx;
				}
				.item-info{
					flex:1;
					.item-name{
						font-weight: 500;
						font-size: 28rpx;
					}
					.item-val{
						display: inline-block;
						font-size: 20rpx;
						box-sizing: border-box;
						border-radius: 4px;
						
						.item-val-text{
							display: inline-block;
							box-sizing: border-box;
							padding: 4rpx 10rpx;
						}
						.item-val-specifica-title{
							border-right: 1px solid #ff551a;
							background-color: #FFE1D6;
							color: #FF551A;
							border-top-left-radius: 4px;
							border-bottom-left-radius: 4px;
						}
						.item-val-specifica-text{
							color: #FF551A;
						}
						.item-val-owner-title{
							border-right: 1px solid #C09A87;
							background-color: #FAF1DF;
							color: #B88D77;
							border-top-left-radius: 4px;
							border-bottom-left-radius: 4px;
						}
						.item-val-owner-text{
							color: #B88D77;
						}
					}
					.item-price{
						font-weight: bold;
						color: #ff551a;
					}
					.item-stock{
						color: #999;
					}
					.item-add{
						background-color: #FFEEC7;
						border-radius: 24px;
						box-sizing: border-box;
						padding:10rpx 20rpx;
						border: 1px solid #C88D00;
						color: #C88D00;
						font-size: 28rpx;
					}
					.item-no-add{
						color: #9D9D9D;
						background: #E7E7E7;
						border: 1px solid #9D9D9D;
					}
				}
			}
		}
		
		.chose-num {
			// height: 250rpx;
			width: 100%;
			position: fixed;
			bottom: 0;
			background-color: #FFFFFF;
			z-index: 999;
			box-sizing: border-box;
			padding-bottom: 20rpx;
			/* #ifdef APP-PLUS */
			padding-bottom: env(safe-area-inset-bottom);
			/* #endif */
			.sellunit-box{
				background-color: #f8f8f8;
				color:#999;
				box-sizing: border-box;
				padding: 20rpx 30rpx;
			}
		}
		.shop-cart-container{
			position: fixed;
			bottom: 200rpx;  
			right: 14rpx; 
			z-index: 887;
			width: 120rpx; 
			height: 120rpx; 
			border-radius: 50%; 
			background-color: #FFBB1A;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow: 0px 0px 18px 2px rgba(6,0,1,0.1);
			transition: all 0.5s ease;
		}
		.shop-cart-active{
			right: -60rpx;
			opacity:0.4;
			transition: all 0.5s ease;
		}
	}


</style>
